<?php

namespace App\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\RoleRepository;
use App\Entities\Role;
use App\Entities\PermissionRole;
use App\Entities\Permission;
use App\Validators\RoleValidator;

/**
 * Class RoleRepositoryEloquent.
 *
 * @package namespace WanyueLayuiAdmin\Repositories;
 */
class RoleRepositoryEloquent extends BaseRepository implements RoleRepository
{

    public function create(array $data)
    {
        $data['code'] = \Illuminate\Support\Str::random(20);
        return static::firstOrCreate($data);
    }

    public function relate($data, $id)
    {
        PermissionRole::where('role_id', $id)->delete();
        foreach ($data['permissions'] as $permission_id) {
            $created = PermissionRole::firstOrCreate([
                'permission_id' => $permission_id,
                'role_id' => $id,
            ]);
            if (!$created) {
                return false;
            }
        }
        return $created;
    }

    public function related($id)
    {
        $ids = PermissionRole::where('role_id', $id)
            ->pluck('permission_id')
            ->toArray();
        return Permission::whereIn('id', $ids)
            ->pluck('id')
            ->filter(function($id) {
                return !Permission::where('pid', $id)->value('id');
            })->values();
    }

    public function format()
    {
        return static::findWhere([['is_disabled', '=', 0]])->map(function($item) {
            return ['title' => $item['name'], 'value' => $item['id']];
        });
    }


    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Role::class;
    }

    /**
    * Specify Validator class name
    *
    * @return mixed
    */
    public function validator()
    {

        return RoleValidator::class;
    }


    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {

    }

}
